// import { prompt } from "@/utils/T";
import {request} from "ice";
import {lodash as _} from "@/utils";

import {childConfig} from "@/config";

type IOptions = {
  headers?: any;
  instanceName?: 'ops';
}

/**
 * 解决乱码问题 encode header
 * @param headers
 */
const encodeHeader = (headers: any) => {
  Object.keys(headers).forEach(
    (key) => (headers[key] = encodeURI(headers[key]))
  );

  return headers;
};

/**
 *
 * @param options
 * @returns {Promise<any>}
 * @private
 */
const _request = (options: IOptions) => {
  const successCode = childConfig.apiSuccessCode;

  return new Promise((resolve, reject) => {
    // encode header
    if (!_.isEmpty(options.headers)) {
      options.headers = encodeHeader(options.headers);
    }
    request(options)
      .then((resp: IResponse) => {
        /* 自定义标准接口标准 */
        const code = resp.code || resp.status;
        if (successCode == code) {
          resolve(resp);
        }
        reject(resp);
      })
      .catch((error: any) => {
        reject({
          status: 'ERROR',
          data: null,
          msg: error.msg,
        });
      });
  });
};


/**
 * get请求
 * @param url
 * @param params
 * @param options
 */
export function get(url: string, params?: object, options: IOptions = {}) {
  const headers = {};
  if (options.headers) {
    options.headers = Object.assign(headers, options.headers);
  }

  options = Object.assign(
    {
      url,
      method: 'get',
      params,
    },
    options
  );

  return _request(options);
}

/**
 * post json请求
 * @param {string} url
 * @param {object} params
 * @param {object} options
 * @returns {Promise}
 */
export function postJSON(url: string, params: object = {}, options: IOptions = {}) {
  const headers = {
    'Content-Type': 'application/json',
  };
  if (options.headers){
    options.headers = Object.assign(headers, options.headers);
  }
  options = Object.assign(
    {
      url,
      method: 'post',
      data: params,
      headers,
    },
    options
  );

  return _request(options);
}

/**
 * 并发执行多个请求
 * @returns {Promise.<*>}
 */
export function all(args: any[]) {
  return Array.isArray(args) ? Promise.all(args) : Promise.all([...arguments]);
}
